package com.example.statistics.ui.bank

import android.graphics.Rect
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.RadioGroup.OnCheckedChangeListener
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.statistics.R
import com.example.statistics.bean.Bank
import com.example.statistics.bean.BankFlowBean
import com.example.statistics.common.BaseLoadingListActivity
import com.example.statistics.ex.*
import com.example.statistics.net.UrlConfig
import com.example.statistics.utils.Constants
import com.example.statistics.utils.activityFinish
import com.example.statistics.utils.activityForResult
import com.jhj.imageselector.utils.selected
import com.jhj.slimadapter.SlimAdapter
import com.jhj.slimadapter.holder.ViewInjector
import kotlinx.android.synthetic.main.filter_bank_flow.*
import kotlinx.android.synthetic.main.filter_bank_flow.view.*
import kotlinx.android.synthetic.main.layout_search_bar.*
import org.jetbrains.anko.dip
import org.jetbrains.anko.sdk27.coroutines.onClick
import org.jetbrains.anko.toast

class BankFlowListActivity : BaseLoadingListActivity<BankFlowBean>() {
    var action: String? = ""
    var accountId: Int = 0
    var filterType = ""
    var filterStatus = ""
    var selectedBank: Bank? = null

    override val title: String
        get() = "银行流水"
    override val itemLayoutRes: Int
        get() = R.layout.list_item_bank_flow
    override val url: String
        get() = UrlConfig.BANK_FLOW_LIST

    override val inputSearch: Boolean
        get() = true

    override val inputSearchFunc: (BankFlowBean, String) -> Boolean = { bean, str ->
        bean.money.toString().contains(str)
    }

    override val httpParams: MutableList<Pair<String, String>>
        get() {
            val type = intent.getStringExtra(Constants.TYPE).orEmpty()
            action = intent.getStringExtra(Constants.ACTION)
            val params = mutableListOf<Pair<String, String>>()
            accountId = intent.getIntExtra("accountId", 0)

            if (accountId != 0) {
                params.add("accountId" to accountId.toString())
            }
            if (!action.isNullOrEmpty()) {
                params.add("action" to "selector")

            }
            params.add("type" to type)
            return params
        }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        iv_search_filter.visibility = View.VISIBLE



        topBarRightImage {
            activityForResult<BankFlowAddActivity>(
                "accountId" to accountId
            ) {
                refresh()
            }
        }

        initDrawerLayout(R.layout.filter_bank_flow) { view, drawerLayout ->
            httpGet<List<Bank>>(UrlConfig.BANK_ACCOUNT_LIST, config = {
                isShowDialog = true
                listParams = listOf()
            }) { bankList ->
                view.rg_type.setOnCheckedChangeListener { _, checkedId ->
                    filterType = when (checkedId) {
                        R.id.rb_type_expense -> "支出"
                        R.id.rb_type_income -> "收入"
                        else -> ""

                    }
                }
                view.rg_status.setOnCheckedChangeListener { _, checkedId ->
                    filterStatus = when (checkedId) {
                        R.id.rb_status_settlement -> "已结算"
                        R.id.rb_status_unplenary -> "未结算"
                        else -> ""
                    }
                }
                view.recycler_account.layoutManager = GridLayoutManager(this, 2)
                view.recycler_account.addItemDecoration(object : RecyclerView.ItemDecoration() {
                    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
                        super.getItemOffsets(outRect, view, parent, state)
                        //不是第一个的格子都设一个左边和底部的间距
                        outRect.left = dip(10);
                        outRect.bottom = dip(10);
                        //由于每行都只有3个，所以第一个都是3的倍数，把左边距设为0
                        if (parent.getChildLayoutPosition(view) % 2 == 0) {
                            outRect.left = 0;
                        }
                    }
                })
                var selectorTextView: TextView? = null
                slimAdapter<Bank>(R.layout.list_item_bank_selector) {
                    var str = it.bank
                    if (it.cardNumber.length > 4) {
                        val number = it.cardNumber.replace(" ", "")
                        str += number.substring(number.length - 4, number.length)
                    }
                    this.text(R.id.text_view, str)
                        .clicked { view ->
                            selectorTextView?.isSelected = false
                            view.isSelected = !view.isSelected
                            selectorTextView = view as TextView
                            selectedBank = it
                        }
                }.setDataList(bankList.orEmpty()).attachTo(view.recycler_account)
            }


        }
    }

    override fun filter() {
        super.filter()
        filterParams.put("type" to filterType)
        filterParams.put("status" to filterStatus)
        filterParams.put("accountId" to selectedBank?.ID)
    }

    override fun resetFilter(view: View) {
        super.resetFilter(view)
        view.rg_type.clearCheck()
        view.rg_status.clearCheck()
    }

    override fun itemViewConvert(adapter: SlimAdapter, injector: ViewInjector, bean: BankFlowBean, position: Int) {

        val color = if (bean.type == "收入") getResColor(R.color.red) else getResColor(R.color.green)
        injector.text(R.id.tv_bank, bean.account)
            .text(R.id.tv_money, bean.money.toString() + " | " + bean.balance)
            .textColor(R.id.tv_money, color)
            .text(R.id.tv_date, bean.date.goTimeFormat("yyyy-MM-dd ") + bean.time.substring(0, 5))
            .clicked {
                if (action == Constants.SELECTOR) {
                    activityFinish(Constants.DATA to bean)
                }
            }
            .onActionLongClicked(
                "编辑" to {
                    if (bean.money == bean.balance) {
                        activityForResult<BankFlowAddActivity>(Constants.ID to bean.ID) {
                            refresh()
                        }
                    } else {
                        toast("已关联订单，不可修改")
                    }
                },

                "删除" to {
                    if (bean.money == bean.balance) {
                        messageDialog(msg = "是否删除${bean.account + bean.type + bean.money}？") { _, _ ->
                            httpGet<Any>(UrlConfig.BANK_FLOW_DELETE, config = {
                                listParams = listOf("id" to bean.ID)
                            }) {
                                refresh()
                            }
                        }
                    } else {
                        toast("已关联订单，不可删除")
                    }
                }
            )


    }

}